package com.pxmeta.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.party.entity.dto.AddDecorationDTO;
import com.pxmeta.product.entity.Shop;
import com.pxmeta.product.entity.UserShop;
import com.pxmeta.product.mapper.ShopMapper;
import com.pxmeta.product.service.IShopService;
import com.pxmeta.product.service.IUserShopService;
import com.pxmeta.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private IUserService userService;
    private final IUserShopService userShopService;
    @Override
    public void buy(Long userId, Long shopId, Integer days) {
        Shop shop = this.getById(shopId);
        Integer price = shop.getPrice();
        int totalPrice = price * days;
        //扣减余额
        userService.subBalance(userId, totalPrice);
        //将虚拟礼物放入背包。
        userShopService.add(userId, shop, days);
    }

    @Override
    public void useDecoration(Long userId, Long shopId) {
        LambdaQueryWrapper<UserShop> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserShop::getUserId, userId)
                .eq(UserShop::getShopId, shopId);

        UserShop userShop = userShopService.getOne(wrapper, false);
        if (userShop == null){
            throw new ServiceException("装饰不存在！");
        }

        //将使用中的置为空
        nonuseDecoration(userId, userShop.getShopType());
        userShop.setIsUse(Boolean.TRUE);
        userShopService.updateById(userShop);
    }

    @Override
    public List<Shop> getUserDecoration(Long userId, Integer type, Boolean isUse) {
        LambdaQueryWrapper<UserShop> wrapper = Wrappers.lambdaQuery();
        if (isUse != null){
            wrapper.eq(UserShop::getIsUse, isUse);
        }
        if (type != null){
            wrapper.eq(UserShop::getShopType,type);
        }
        wrapper.eq(UserShop::getUserId, userId)

                .orderByDesc(UserShop::getCreateTime);

        List<UserShop> userShops = userShopService.list(wrapper);

        List<Long> shopIds = userShops.stream().map(UserShop::getShopId).collect(Collectors.toList());
        if (shopIds.isEmpty()){
            return Lists.newArrayList();
        }
        List<Shop> shops = this.listByIds(shopIds);

        for (Shop shop : shops) {
            for (UserShop userShop : userShops) {
                if (shop.getId().equals(userShop.getShopId())){
                    shop.setIsUse(userShop.getIsUse());
                    break;
                }
            }
        }
        return shops;
    }

    @Override
    public List<Shop> getUserUsedDecoration(Long userId) {


        return getUserDecoration(userId, null, Boolean.TRUE);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void nonuseDecoration(Long userId, Integer type) {
        LambdaQueryWrapper<UserShop> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserShop::getUserId, userId)
                .eq(UserShop::getShopType, type)
                .eq(UserShop::getIsUse, Boolean.TRUE);

        UserShop userShop = userShopService.getOne(wrapper);
        if (userShop != null){
            userShop.setIsUse(Boolean.FALSE);
            userShopService.updateById(userShop);
        }

    }

    @Override
    public List<Shop> getDecorationByType(Long userId, Integer category, Integer type) {
        LambdaQueryWrapper<Shop> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Shop::getType,type)
                .eq(Shop::getCategory,category)
                .orderByDesc(Shop::getCreateTime);

        List<Shop> userDecoration = getUserDecoration(userId, type, Boolean.TRUE);
        List<Shop> shops = this.list(wrapper);
        if (!userDecoration.isEmpty()){
            List<Long> shopIds = userDecoration.stream().map(Shop::getId).collect(Collectors.toList());
            for (Shop shop : shops) {
                if (shopIds.contains(shop.getId())){
                    shop.setIsUse(Boolean.TRUE);
                }
            }
        }


        return shops;
    }

    @Override
    public IPage<Shop> getDecorationList(Integer page, Integer size, Integer category) {
        LambdaQueryWrapper<Shop> wrapper = Wrappers.lambdaQuery();
        if (category != null){
            wrapper.eq(Shop::getCategory, category);
        }
        return this.page(new Page<>(page,size),wrapper);

    }

    @Override
    public void addDecoration(AddDecorationDTO dto) {
        Shop shop = new Shop();
        shop.setCategory(dto.getCategory());
        shop.setIcon(dto.getIcon());
        shop.setMaterialUrl(dto.getMaterialUrl());
        shop.setName(dto.getName());
        shop.setPrice(dto.getPrice());
        String categoryName = getCategoryName(dto.getCategory());
        shop.setCategoryName(categoryName);
        shop.setType(1);
        this.save(shop);
    }


    private String getCategoryName(Integer category){
        String name = "";
        if (category == 1){
            name = "头像框";
        }else if (category == 2){
            name = "聊天气泡";
        }else if (category == 3){
            name = "麦位音波";
        }else if (category == 4){
            name = "昵称挂件";
        }else if (category == 5){
            name = "入场特效";
        }else if (category == 6){
            name = "个人名牌";
        }else if (category == 7){
            name = "主页特效";
        }
        return name;
    }
}
